/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.portalnahouby.implementation.daoimplementation;

import cz.muni.fi.pa165.portalnahouby.api.dto.PickerDTO;
import cz.muni.fi.pa165.portalnahouby.implementation.daointerface.PickerDAO;
import cz.muni.fi.pa165.portalnahouby.implementation.entity.Picker;
import cz.muni.fi.pa165.portalnahouby.implementation.entity.Visit;
import cz.muni.fi.pa165.portalnahouby.implementation.util.EntityDTOConvertor;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of PickerDAO interface
 *
 * @author Lukas Marica
 */
@Repository
@Transactional
public class PickerDAOImpl implements PickerDAO {

	@PersistenceContext
	private EntityManager em;

	@Override
	public void addPicker(Picker picker) {
		if (picker == null) {
			throw new IllegalArgumentException("Picker cannot be null");
		}
		if (picker.getId() != null) {
			throw new IllegalArgumentException("New picker has to have null ID");
		}

		em.persist(picker);
	}

	@Override
	public void editPicker(Picker picker) {
		if (picker == null) {
			throw new IllegalArgumentException("Picker cannot be null");
		}
		if (picker.getId() == null) {
			throw new IllegalArgumentException("Picker's ID cannot be null");
		}
		
		if( picker.getPass() == null || picker.getPass().isEmpty() )
		{
			Picker originalPicker = em.find(Picker.class, picker.getId());
			picker.setPass(originalPicker.getPass());
		}		

		em.merge(picker);
	}

	@Override
	public void deletePicker(Long id) {
		if (id == null) {
			throw new IllegalArgumentException("ID cannot be null");
		}

		Picker picker = em.find(Picker.class, id);

		em.remove(picker);
	}

	@Override
	public Picker findPicker(Long id) {
		if (id == null) {
			throw new IllegalArgumentException("ID cannot be null");
		}

		return em.find(Picker.class, id);
	}

	@Override
	public Picker findPickerByLoginPass(String name, String pass) {
		TypedQuery<Picker> query = em.createQuery("SELECT p FROM Picker p WHERE p.login = :name AND p.pass = :pass", Picker.class);
		query.setParameter("name", name);
		query.setParameter("pass", pass);
		List<Picker> pickers = query.getResultList();
		if( ! pickers.isEmpty() )
		{
			return pickers.get(0);
		}
		else
		{
			return null;
		}
	}

	@Override
	public List<Picker> getAllPickers() {
		return em.createQuery("SELECT p FROM Picker p", Picker.class).getResultList();
	}
}
